package de.koller.kelvin.engine.landscape;

import de.koller.aframe.util.thread.ILoopHandler;
import de.koller.aframe.util.thread.ThreadRootHandle;
import de.koller.kelvin.KNode;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class LandscapeGenerator extends KNode implements ILoopHandler {
	
	public static final int BUFFERSIZE = 10;
	
	private final ThreadRootHandle threadHandler = new ThreadRootHandle( "landscape gen" );

	private final List<GenCommand> gens = Collections.synchronizedList( new LinkedList<GenCommand>() );
	private final SurfaceGenerator surfaceGenerator = new SurfaceGenerator();
	
	@Override
	protected void init() {
		super.init();
		
		threadHandler.start();
		threadHandler.setLoopHandler( this );
	}

	@Override
	protected void release() {
		super.release();
		
		threadHandler.stop();
	}

	public void generate( LandscapeTile tile, LandscapeDisplay display ) {
		gens.add( 0, new GenCommand( tile, display ) );
	}
	
	@Override
	public void loopHandle() {
		if( gens.isEmpty() )
			return; //@Todo handle busy loop!
		
		while( gens.size() > BUFFERSIZE )
			gens.remove( gens.size() - 1 );
		
		GenCommand g = gens.remove( 0 );
		if( g.display == LandscapeDisplay.Surface )
			surfaceGenerator.setup( g.tile );
	}
	
}
